import requests
import json
from datetime import datetime, timedelta
import time


class jenkins_api(object):


    def __init__(self, jenkins_url, username, password):
        self.jenkins_url = jenkins_url
        self.username = username
        self.password = password

        self.headers = {
            'content-type': 'application/json',
        }


    def get_all_jobs(self):
        # 发送请求并获取响应
        response = requests.get(self.jenkins_url + '/api/json?tree=jobs[name]', auth=(self.username, self.password))

        # 解析JSON响应
        jobs = response.json()['jobs']

        data = []
        # 打印所有job名称
        for job in jobs:
            if job['_class'] == 'com.cloudbees.hudson.plugins.folder.Folder':
                job['file_type'] = 'folder'

            if job['_class'] == 'org.jenkinsci.plugins.workflow.job.WorkflowJob':
                job['file_type'] = 'workflow_job'
                job['folder_name'] = r'没有文件夹'

            if job['_class'] == 'hudson.model.FreeStyleProject':
                job['file_type'] = 'workflow_job'
                job['folder_name'] = r'没有文件夹'

            if job['_class'] == 'hudson.model.ExternalJob':
                job['file_type'] = 'workflow_job'
                job['folder_name'] = r'没有文件夹'
            
            if job['_class'] == 'hudson.maven.MavenModuSet':
                job['file_type'] = 'workflow_job'
                job['folder_name'] = r'没有文件夹'
            
            if job['_class'] == 'hudson.matrix.MatrixProject':
                job['file_type'] = 'workflow_job'
                job['folder_name'] = r'没有文件夹'

            if job['_class'] == 'com.tikal.jenkins.plugins.multijob.MultiJobProject':
                job['file_type'] = 'workflow_job'
                job['folder_name'] = r'没有文件夹'

            if job['_class'] == 'org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject':
                job['file_type'] = 'workflow_job'
                job['folder_name'] = r'没有文件夹'

            job['job_path'] = 'job/' + job['name']
            job['job_full_path'] = self.jenkins_url + '/job/' + job['name']
            data.append(job)
        return data

    def get_folder_jobs(self, folder_name):
        # 发送GET请求获取所有job列表
        url = self.jenkins_url + '/job/' + folder_name + '/api/json?tree=jobs[name,color]'
        response = requests.get(url, auth=(self.username, self.password))

        data = []
        # 解析响应结果并输出所有job的名称
        if response.status_code == 200:
            jobs = response.json()["jobs"]
            for job in jobs:
                # print(job)
                if job['_class'] == 'com.cloudbees.hudson.plugins.folder.Folder':
                    son_folder_url = self.jenkins_url + '/job/' + folder_name + '/job/' + job['name'] + '/api/json?tree=jobs[name,color]'
                    son_folder_response = requests.get(son_folder_url, auth=(self.username, self.password))
                    if son_folder_response.status_code == 200:
                        son_jobs = son_folder_response.json()["jobs"]
                        for son_job in son_jobs:
                            # print(son_job)
                            job['folder_name'] = folder_name
                            job['file_type'] = 'folder_workflow_job'
                            job['job_path'] = folder_name + '/job/' + job['name'] + '/job/' + son_job['name']
                            job['job_full_path'] = self.jenkins_url + '/job/' + folder_name + '/job/' + job['name'] + '/job/' + son_job['name']                               
                else:
                    job['folder_name'] = folder_name
                    job['file_type'] = 'folder_workflow_job'
                    job['job_path'] = folder_name + '/job/' + job['name']
                    job['job_full_path'] = self.jenkins_url + '/job/' + folder_name + '/job/' + job['name']

                data.append(job)
                # print(job)
        else:
            print("Failed to get job list")
        return data

    def get_job_builds_record(self, job_name, file_type):
        url = None

        if file_type == 'folder_workflow_job':
            url = self.jenkins_url + '/job/' + job_name + '/api/json?tree=builds[number,timestamp,result,duration]'

        if file_type == 'workflow_job':
            url = self.jenkins_url + '/' + job_name + '/api/json?tree=builds[number,timestamp,result,duration]'

        print(url)
        # 发送GET请求获取job的构建记录
        response = requests.get(url, auth=(self.username, self.password))

        # 解析响应结果并输出构建记录
        data = []
        if response.status_code == 200:
            builds = response.json()["builds"]
            for build in builds:
                # print(f"构建编号：{build['number']}")
                # print(f"构建时间：{self.timestamp_to_time(build['timestamp'])}")
                # print(f"构建结果：{build['result']}")
                # print("----------")

                build['build_date'] = self.timestamp_to_time(build['timestamp'])
                data.append(build)
                # print(build)
        else:
            print("获取构建记录失败")
        return data

    def timestamp_to_time(self, timestamp):
        date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp / 1000))
        return date

    def get_all_computer(self):
        # 构建请求URL
        url = self.jenkins_url + '/computer/api/json?tree=computer[displayName,offline]'

        # 发送HTTP请求
        response = requests.get(url, auth=(self.username, self.password), headers=self.headers)

        # 解析返回的JSON数据
        data = response.json()
        # 获取节点信息
        nodes = data['computer']
        return nodes

    def get_wait_queue(self):
        url = self.jenkins_url + '/queue/api/json?pretty=true'

    def get_jenkins_plugins(self):
        url = self.jenkins_url + '/pluginManager/api/json?depth=1'

        # 发送HTTP请求
        response = requests.get(url, auth=(self.username, self.password), headers=self.headers)
        plugins = response.json()["plugins"]

        for plugin in plugins:
            plugin_name = plugin["shortName"]
            plugin_version = plugin["version"]
            plugin_status = plugin["active"]  # 插件状态为True表示正常工作，False表示未启用或有问题
            print(f"Plugin: {plugin_name}, Version: {plugin_version}, Status: {plugin_status}")

    def get_version(self):
        url = self.jenkins_url + '/api/json'

    def get_job_bulds_by_url(self, job_url):
        url = job_url + '/api/json?tree=builds[number,timestamp,result,duration,color]'
        print(url)

        # 发送GET请求来获取job的构建记录
        response = requests.get(url, auth=(self.username, self.password))

        # 解析相应结果并输出构建记录
        data = []
        if response.status_code == 200:
            builds = response.json()["builds"]
            for build in builds:
                build['build_date'] = self.timestamp_to_time(build['timestamp'])
                data.append(build)
                # print(build)
        else:
            print("获取构建记录失败")
        return data

    def get_slave_node_job(self, node_name):
        url = self.jenkins_url + '/computer/' + node_name + '/api/json?depth=2'

    def stop_jenkins_job(self, job_url, build_number):
        # 构建停止API的URL
        url = job_url + '/' + str(build_number) + '/stop'

        # 发送POST请求停止构建
        response = requests.post(url, auth=(self.username, self.password))
        
        if response.status_code == 200:
            print('Successfully stopped job: ' + url)
        else:
            print(f'Failed to stop job: ' + url)

        return result

